<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Express as LibraryExpress;
use app\common\library\Wxpay;
use app\common\model\Cart;
use app\common\model\Express;
use app\common\model\MoneyLog;
use app\common\model\Order as ModelOrder;
use app\common\model\Review;
use app\common\model\ScoreLog;
use think\Db;

/**
 *订单接口
 */
class Order extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 订单下单
     *
     */
    public function addOrder()
    {
        $post = request()->post();
        $uid =  $this->auth->id;
        extract($post);
        if (!isset($ids) || empty($ids)) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            if ($type == '1') {
                $cart_ids = $ids;
                $goods = Cart::getGoods($cart_ids, $uid);
            } else {
                $param = [
                    'goods_id' => $ids,
                    'num' => $num,
                    'type' => $type,
                    'uid' => $uid,
                ];
                $cart_ids = Cart::addCart($param);
                $goods = Cart::getGoods($cart_ids, $uid);
            }
            $order = new ModelOrder();
            $data = [
                'goods' => $goods,
                'address_id' => $address_id ?? 0,
                'uid' => $uid,
            ];
            $orderinfo = $order->yuOrder($data);
            if ($add_type == 'info') {
                if (!is_array($orderinfo)) {
                    exception('错误');
                }
            } else {
                $orderinfo = $order->addData($orderinfo, $uid);
                if (!$orderinfo) {
                    exception('下单失败');
                }
                Cart::delCart($uid, $cart_ids);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($add_type != 'info') {
            $orders = ModelOrder::get($orderinfo['id']);
            queue('app\common\job\Order', $orders, 1800, 'order1226');
        }
        return $this->success('', $orderinfo);
    }
    /**
     * 立即付款
     *
     */
    public function pay()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        // if (!isset($pay_type)) {
        //     $this->error('请选择支付方式');
        // }
        Db::startTrans();
        try {
            $order = ModelOrder::get($id);
            if ($order['pay_money'] <= 0) {
                $res = $order->save(['status' => 1, 'paytime' => time()]);
                if ($res) {
                    ScoreLog::income($order->id, $order->total_points, 2, 200, $order->sn);
                } else
                    exception('支付失败');
            } else {
                $userInfo = $this->auth->getUser();
                $sdk = Wxpay::wxpay($order->sn, $order['pay_money'], $userInfo['openid']);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('提交支付失败：' . $e->getMessage());
        }
        $this->success('', $sdk ?? []);
    }
    //订单列表
    public function orderList()
    {
        $param = request()->param();
        $uid =  $this->auth->id;
        extract($param);
        $order = new ModelOrder();
        if ($status == 'all') {
            $order->where('order.status', '<>', '-1');
        } elseif ($status == 3) {
            $order->whereIn('order.status', ['3', '4']);
        } else {
            $order->where('order.status', $status);
        }
        $list = $order->with(['user', 'address', 'info'])->where('order.user_id', $uid)->order('id desc')->paginate(10);
        $this->success('请求成功', $list);
    }
    //订单详情
    public function orderInfo()
    {
        $param = request()->param();
        extract($param);
        $order = new ModelOrder();
        $data = $order->get($id, ['user', 'address', 'info']);
        $this->success('请求成功', $data);
    }

    /**
     * 查看物流
     *
     */
    public function logistics()
    {
        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = ModelOrder::get($id);
        if (!$order) {
            $this->error('订单不存在');
        }
        $express = new LibraryExpress($order);
        $wuliu = $express->getOrderTracesByJson();
        $wuliu['express_name'] = Express::where('customer', $order['express_com'])->value('name');
        $wuliu['address'] = $order['address'];
        $wuliu['nu'] = $order['express_no'];
        $this->success('', $wuliu);
    }

    /**
     * 确认订单
     *
     */
    public function confirmOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            $order = ModelOrder::get($id);
            if (!$order) {
                exception('订单不存在');
            }
            if ($order->status != 2) {
                exception('订单状态错误');
            }
            $order->save(['status' => 3]);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error('操作失败：' . $th->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * 订单评论
     *
     */
    public function comment()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = $this->request->post();
        extract($post);
        if (!isset($order_id) || empty($order_id)) {
            $this->error('参数错误');
        }
        if (!isset($data) || empty($data)) {
            $this->error('提交错误');
        }
        $Review = new Review();
        $res = $Review->addReview($post, $this->auth->id);
        if ($res === true) {
            $this->success('评论成功');
        }
        $this->error('评论失败:' . $res);
    }
    /**
     * 再来一单
     *
     */
    public function moreOrder()
    {
        $get = request()->param();
        $uid =  $this->auth->id;
        extract($get);

        $goods = Cart::getProducts($order_id, $uid);
        if (!$goods) {
            $this->error('商品不存在');
        }
        Db::startTrans();
        try {
            $order = new ModelOrder();
            $data = [
                'goods' => $goods,
                'address_id' => $address_id ?? 0,
                'uid' => $uid,
            ];
            $orderinfo = $order->moreOrder($data);
            if ($add_type == 'info') {
                if (!is_array($orderinfo)) {
                    exception('错误');
                }
            } else {
                $orderinfo = $order->addData($orderinfo, $uid);
                if (!is_array($orderinfo)) {
                    exception('下单失败');
                }
            }
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($add_type != 'info') {
            $order = ModelOrder::get($orderinfo['id']);
            queue('app\common\job\Order', $order, 1800,'order1226');
        }
        return $this->success('', $orderinfo);
    }
}
